<template>
  <div class="wechat-native-pay">
    <el-card class="pay-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>微信扫码支付</span>
          <span class="amount-text">订单金额：￥{{ formattedAmount }}</span>
        </div>
      </template>

      <!-- 初始状态 -->
      <div v-if="!hasCreatedOrder" class="pay-stage">
        <p class="stage-title">请确认订单信息后发起支付</p>
        <el-button
          type="primary"
          size="large"
          :loading="loading"
          @click="startPayment"
        >
          发起支付
        </el-button>
        <p class="hint">点击上方按钮生成微信二维码，完成扫码支付</p>
        <p v-if="errorMsg" class="error-text">{{ errorMsg }}</p>
      </div>

      <!-- 支付成功 -->
      <div v-else-if="isPaid" class="result-stage success">
        <el-result
          icon="success"
          title="支付成功"
          sub-title="正在跳转至订单详情..."
        />
      </div>

      <!-- 支付失败或超时 -->
      <div v-else-if="errorMsg" class="result-stage error">
        <el-result
          icon="error"
          title="支付未完成"
          :sub-title="errorMsg"
        >
          <template #extra>
            <el-button type="primary" @click="restartPayment" :loading="loading">
              重新支付
            </el-button>
          </template>
        </el-result>
      </div>

      <!-- 支付中 -->
      <div v-else class="pay-stage processing">
        <div class="qr-wrapper">
          <qrcode-vue :value="codeUrl" :size="200" level="M" />
        </div>
        <p class="stage-title">请使用微信扫描二维码完成支付</p>
        <p class="status-text">
          支付状态：{{ statusMessage }}
        </p>
        <p class="countdown">支付倒计时：{{ countdown }} 秒</p>
        <p class="hint">若长时间未完成，可点击下方按钮重新发起</p>
        <el-button type="warning" plain size="default" @click="restartPayment" :loading="loading">
          重新发起支付
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onBeforeUnmount, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import QrcodeVue from 'qrcode.vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const props = defineProps({
  orderId: {
    type: [String, Number],
    required: false,
    default: null
  },
  amount: {
    type: Number,
    required: false,
    default: 0.01
  },
  /**
   * 可选：支付接口基础路径，默认同源
   */
  baseUrl: {
    type: String,
    default: ''
  }
})

// 从路由参数获取订单ID和金额（如果props未传入）
const actualOrderId = computed(() => {
  return props.orderId || route.query.orderId || ''
})

const actualAmount = computed(() => {
  const amountFromQuery = route.query.amount ? parseFloat(route.query.amount) : null
  return props.amount || amountFromQuery || 0.01
})

onMounted(() => {
  // 如果没有订单ID，提示并返回
  if (!actualOrderId.value) {
    ElMessage.warning('订单信息缺失，正在返回...')
    setTimeout(() => {
      router.push('/vip-upgrade')
    }, 2000)
  }
})

const loading = ref(false)
const codeUrl = ref('')
const outTradeNo = ref('')
const isPaid = ref(false)
const errorMsg = ref('')
const countdown = ref(0)
const lastTradeState = ref('')

const countdownTimer = ref(null)
const pollingTimer = ref(null)

const formattedAmount = computed(() => actualAmount.value.toFixed(2))
const hasCreatedOrder = computed(() => !!codeUrl.value || !!outTradeNo.value)

const statusMessage = computed(() => {
  if (isPaid.value) return '支付成功'
  if (lastTradeState.value) return tradeStateMap[lastTradeState.value] || lastTradeState.value
  return '等待支付...'
})

const tradeStateMap = reactive({
  SUCCESS: '支付成功',
  NOTPAY: '待支付',
  USERPAYING: '用户支付中',
  CLOSED: '交易已关闭',
  REVOKED: '已撤销',
  PAYERROR: '支付失败',
  REFUND: '转入退款'
})

const CREATE_URL = `${props.baseUrl}/create/`
const QUERY_URL = `${props.baseUrl}/query/`

async function startPayment() {
  if (!actualOrderId.value) {
    errorMsg.value = '订单信息异常，请刷新后重试'
    return
  }
  resetState()
  loading.value = true
  try {
    const { data } = await axios.post(CREATE_URL, { order_id: actualOrderId.value })
    if (!data?.success || !data?.code_url || !data?.out_trade_no) {
      throw new Error(data?.message || '创建订单失败，请重试')
    }
    codeUrl.value = data.code_url
    outTradeNo.value = data.out_trade_no
    countdown.value = 180
    startCountdown()
    startPolling()
  } catch (err) {
    errorMsg.value = err?.message || '创建订单失败，请稍后再试'
  } finally {
    loading.value = false
  }
}

function startCountdown() {
  clearCountdown()
  countdownTimer.value = window.setInterval(() => {
    if (countdown.value <= 1) {
      handleTimeout()
    } else {
      countdown.value -= 1
    }
  }, 1000)
}

function startPolling() {
  clearPolling()
  pollingTimer.value = window.setInterval(queryPaymentStatus, 3000)
  // 立即查询一次
  queryPaymentStatus()
}

async function queryPaymentStatus() {
  if (!outTradeNo.value) return
  try {
    const { data } = await axios.get(QUERY_URL, {
      params: { out_trade_no: outTradeNo.value }
    })
    if (!data?.success) {
      throw new Error(data?.message || '查询支付状态失败')
    }
    lastTradeState.value = data.trade_state || ''
    if (data.is_paid || data.trade_state === 'SUCCESS') {
      handlePaymentSuccess()
    }
  } catch (err) {
    console.error('query payment error:', err)
    errorMsg.value = err?.message || '查询支付状态失败，请稍后重试'
    clearCountdown()
    clearPolling()
  }
}

function handlePaymentSuccess() {
  isPaid.value = true
  clearCountdown()
  clearPolling()
  ElMessage.success('支付成功，正在跳转...')
  window.setTimeout(() => {
    // 如果是VIP支付，跳转到VIP升级页面；否则跳转到订单详情
    if (route.path === '/vip-pay') {
      router.push('/vip-upgrade')
    } else {
      router.push(`/order/detail/${actualOrderId.value}`)
    }
  }, 2000)
}

function handleTimeout() {
  clearCountdown()
  clearPolling()
  countdown.value = 0
  errorMsg.value = '支付超时，请重新发起'
}

function restartPayment() {
  resetState()
  startPayment()
}

function resetState() {
  clearCountdown()
  clearPolling()
  errorMsg.value = ''
  isPaid.value = false
  lastTradeState.value = ''
  codeUrl.value = ''
  outTradeNo.value = ''
  countdown.value = 0
}

function clearCountdown() {
  if (countdownTimer.value) {
    window.clearInterval(countdownTimer.value)
    countdownTimer.value = null
  }
}

function clearPolling() {
  if (pollingTimer.value) {
    window.clearInterval(pollingTimer.value)
    pollingTimer.value = null
  }
}

onBeforeUnmount(() => {
  clearCountdown()
  clearPolling()
})
</script>

<style scoped>
.wechat-native-pay {
  display: flex;
  justify-content: center;
  padding: 24px;
}

.pay-card {
  width: 100%;
  max-width: 480px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.amount-text {
  font-size: 16px;
  color: #00c293;
}

.pay-stage {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  text-align: center;
}

.stage-title {
  font-size: 18px;
  margin: 0;
  color: #333;
}

.hint {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.error-text {
  color: #f56c6c;
  margin: 0;
  font-size: 14px;
}

.qr-wrapper {
  padding: 12px;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  background: #fafafa;
}

.status-text {
  margin: 0;
  font-size: 15px;
  color: #333;
}

.countdown {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #f56c6c;
}

.result-stage {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

@media (max-width: 600px) {
  .pay-card {
    max-width: 100%;
  }
  .wechat-native-pay {
    padding: 12px;
  }
  .amount-text {
    font-size: 14px;
  }
  .stage-title {
    font-size: 16px;
  }
}
</style>


